<template>
  <div class="app-container">
    <!-- 1.表头部分 -->
    <el-row>
      <el-col>
        <el-input v-model="searchQuery.searchText" size="mini" class="searchClass" highlight-first-item style="width: 200px" placeholder="输入姓名" @keyup.enter.native="handleFilter" />
        <el-button size="mini" style="margin-left: 10px;" type="topsmallcss" round icon="el-icon-search" @click="handleFilter()">搜索</el-button>
        <el-button size="mini" round style="margin-left: 10px;" type="topsmallcss" icon="el-icon-refresh-right" @click="reset()">重置</el-button>
        <div style="float:right;overflow:hidden;">
          <el-button class="filter-item" style="margin-left: 10px;" type="addcss" size="mini"  round icon="el-icon-circle-plus-outline" @click="handleCreate">增加</el-button>
        </div>
      </el-col>
    </el-row>
    <!-- 2.表格的主体部分 -->
    <el-table :key="tableKey" v-loading="listLoading" :data="list" fit highlight-current-row style="width: 100%;margin-top:15px;" :default-sort="{prop: 'date', order: 'descending'}" @sort-change="sortChange">
      <el-table-column align="center" min-width="60px" label="合同编号" prop="Player_name" sortable>
        <template slot-scope="{ row }">
          {{ row.Player_name }}
        </template>
      </el-table-column>
      <el-table-column label="合同日期" min-width="60px" align="center" prop="Injury_time" sortable>
        <template slot-scope="{ row }">
          <span>{{ dateFormat("YYYY-mm-dd",row.Injury_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="60px" label="产品编号" prop="Injury_type" sortable>
        <template slot-scope="{ row }">
          {{ row.Injury_type }}
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="60px" label="产品规格" prop="Injury_position" sortable>
        <template slot-scope="{ row }">
          {{ row.Injury_position }}
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" min-width="60px" label="产品数量" prop="Injury_level" sortable>
        <template slot-scope="row">
         <template slot-scope="scope"> -->
          <!-- {{ row.Injury_level }} -->
          <!-- {{ scope.row.Injury_level }} -->
        <!-- </template>
      </el-table-column> -->
      <el-table-column label="产品单价" min-width="60px" align="center" prop="Injury_location" sortable>
        <template slot-scope="{ row }">
          <span>{{ row.Injury_location }}</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商名" class-name="status-col" width="110px" prop="Injury_scene" sortable>
        <template slot-scope="{ row }">
          <span>{{ row.Injury_scene }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="供应地点" prop="Nation_doctorname" min-width="60px" sortable>
        <template slot-scope="{ row }">
          {{ row.Nation_doctorname }}
        </template>
      </el-table-column> -->
      <!-- <el-table-column align="center" label="供应方式" min-width="60px" prop="Club_doctorname" sortable>
        <template slot-scope="{ row }">
          {{ row.Club_doctorname }}
        </template> -->
      <!-- </el-table-column> -->
      <el-table-column label="出货日期" min-width="60px" align="center" prop="Recovery_time" sortable>
        <template slot-scope="{ row }">
          <span>{{ dateFormat("YYYY-mm-dd",row.Recovery_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="90px" label="供应电话" prop="Injury_method" sortable>
        <template slot-scope="{ row }">{{ row.Injury_method }}</template>
      </el-table-column>
      <el-table-column label="快捷操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="{ row, $index }">
          <el-button v-waves type="updatacss" size="mini" @click="handleUpdate(row)">修改</el-button>
          <el-button size="mini" type="deletecss" @click="handleDelete(row,$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 2.增加/修改的弹窗部分 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" style="border-radius:14px;">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="top" label-width="90px" style="width: 100%; margin-left: 50px;border-radius:4px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item style="width:80%" prop="Player_name" label="合同编号">
              <!-- <el-select v-model="temp.Player_id" class="filter-item" style="width:80%" filterable placeholder="请选择">
                <el-option v-for="item in allplayerlist" :key="item.Player_id" :label="item.Player_name" :value="item.Player_id" />
              </el-select> -->
              <el-input v-model="temp.Player_name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同日期" prop="Injury_time" style="width:80%">
              <el-date-picker v-model="temp.Injury_time" style="width:100%" type="date" placeholder="请选择日期" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品编号" prop="Injury_type" style="width:80%">
              <el-input v-model="temp.Injury_type" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品规格" style="width:80%">
              <el-input v-model="temp.Injury_position" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item style="width:100%" label="产品数量">
              <el-input v-model="temp.Injury_level"/>
               <el-select v-model="temp.Injury_level" class="filter-item" style="width:80%" placeholder="请填写"> -->
                <!-- <el-option v-for="item in damagelist" :key="item.key" :label="item.key" :value="item.key" /> -->
              <!-- </el-select>
              
            </el-form-item>
          </el-col>  -->
          <el-col :span="12">
            <el-form-item label="产品单价" prop="Injury_location" style="width:80%">
              <el-input v-model="temp.Injury_location" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商名" prop="Injury_scene" style="width:80%">

              <el-input v-model="temp.Injury_scene" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item style="width:80%" label="供应地点" >
              <el-input v-model="temp.Nation_doctorname" />
              <!-- <el-select v-model="temp.Nation_doctorname" class="filter-item" style="width:80%" placeholder="请选择">
                <el-option v-for="item in alldoctorlist" :key="item.User_id" :label="item.Username" :value="item.User_id" /> -->
              <!-- </el-select>
              <el-input v-model="temp.Nation_doctorname" /> -->
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- <el-col :span="12"> -->
            <!-- <el-form-item style="width:80%" label="供应商名"> -->
              <!-- <el-select v-model="temp.Club_doctorname" class="filter-item" style="width:80%" placeholder="请选择">
                <el-option v-for="item in alldoctorlist" :key="item.User_id" :label="item.Username" :value="item.User_id" />
              </el-select> -->
              <!-- <el-input v-model="temp.Club_doctorname" /> -->
            <!-- </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="出货日期" prop="Recovery_time" style="width:80%">
              <el-date-picker v-model="temp.Recovery_time" style="width:100%" type="date" placeholder="请选择日期" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
             <el-form-item label="供应电话" prop="Injury_method" style="width:80%">
              <el-input v-model="temp.Injury_method" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="24">
             <el-form-item style="width:80%" label="供应商名">
              <el-input v-model="temp.Injury_method" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="供应方式" style="width:90%">
              <el-input v-model="temp.Injury_place" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row> -->

      </el-form>
      <div slot="footer" class="dialog-footer" style="height:40px;width:100%;">
        <div style="margin:0 auto;width:350px;">
          <el-button type="cancelcss" style="width:150px;" @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="confirmcss" style="width:150px;margin-left:45px;" @click="dialogStatus === 'create' ? createData() : updateData()">
            确认
          </el-button>
        </div>
      </div>
    </el-dialog>

    <div style="padding-left:30%;background-color:#fff;border-radius:12px;height:40px;margin:15px 0;position:relative;width:100%;">
      <div style="position:absolute;margin:4px auto;padding:0;">
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" style="padding:0;margin:0;border:0;" @pagination="getList" />
        <!-- <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
          <el-table :data="pvData" border fit highlight-current-row style="width: 100%;">
            <el-table-column prop="key" label="Channel" />
            <el-table-column prop="pv" label="Pv" />
          </el-table>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
          </span>
        </el-dialog> -->
      </div>
    </div>
  </div>
</template>

<script>
import { InjuryList, fetchPv } from '@/api/article'
import { addInjury, getAllplayer, getAlldoctor, updateInjury, deleteInjury } from '@/api/injury'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import UploadExcelComponent from '@/components/UploadExcel/index.vue'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]
// const playerNamelist = [
//   { key: '武磊' },
//   { key: '巴图姆' },
//   { key: '梅西' },
//   { key: 'C罗' }
// ]
const doctor1 = [
  { key: '华佗' },
  { key: '张仲景' },
  { key: '扁鹊' }]
const doctor2 = [
  { key: '华佗' },
  { key: '张仲景' },
  { key: '扁鹊' }]

const damagelist = [
  { key: '轻伤' },
  { key: '重伤' },
  { key: '报销' }
]

const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination, UploadExcelComponent },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        比赛: 'success',
        集训: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      thedisable: false,
      tableKey: 0,
      list: null,
      allplayerlist: {},
      alldoctorlist: {},
      total: 0,
      listLoading: true,
      // playerNamelist,
      damagelist,
      doctor1,
      doctor2,
      listQuery: {
        page: 1,
        limit: 20,
        Player_name: undefined,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      searchQuery: {
        page: 1,
        limit: 20,
        searchText: ''
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      // sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      // 状态标签
      statusOptions: ['比赛', '集训'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        Player_name: '',
        Injury_position: '',
        Injury_time: '',
        Injury_type: '',
        Injury_level: '',
        Nation_doctorname: '',
        autoWidth: true,
        Club_doctorname: '',
        Nation_doctorname: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        // Player_name: [
        //   { required: true, message: '需要填写伤员姓名', trigger: 'blur' }
        // ],
        type: [
          { required: true, message: '需要填写受伤类型', trigger: 'change' }
        ],
        // Injury_time: [
        //   {
        //     type: 'date',
        //     required: true,
        //     message: '需要填写时间',
        //     trigger: 'change'
        //   }
        // ],
        Injury_location: [
          { required: true, message: '需要填写产品数量', trigger: 'blur' }
        ],
        Recovery_time: [
          { required: true, message: '时间不能为空' }
        ]
      },
      downloadLoading: false
    }
  },

  created() {
    this.getList()
    //this.getplayerlist()
    //this.getdoctorlist()
    this.gethandle()
  },
  methods: {
    gethandle() {
      if (this.$store.getters.handle.includes('injury')) {
        this.thedisable = false
      } else {
        this.thedisable = true
      }
    },
    getList() {
      this.listLoading = true
      InjuryList(this.listQuery).then((response) => {
        this.list = response.data.value
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 0.3 * 1000)
      })
    },
    getplayerlist() {
      this.listLoading = true
      getAllplayer().then((response) => {
        this.allplayerlist = response.data
        // console.log(this.allplayerlist.data)
        setTimeout(() => {
          this.listLoading = false
        }, 0.01 * 1000)
      })
    },
    getdoctorlist() {
      this.listLoading = true
      getAlldoctor().then((response) => {
        this.alldoctorlist = response.data
        // console.log(this.alldoctorlist)
        setTimeout(() => {
          this.listLoading = false
        }, 0.01 * 1000)
      })
    },
    searchList() {
      this.listLoading = true
      InjuryList(this.searchQuery).then((response) => {
        this.list = response.data.value
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 0.3 * 1000)
      })
    },
    gotolink(row) {
      this.$router.push({ name: 'injurydetail', query: { Player_name: row.Player_name }})
    },
    // 搜索内容
    handleFilter() {
      // this.listQuery.page = 1
      this.searchList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        Injury_time: new Date(),
        title: '',
        status: '比赛',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          addInjury(this.temp).then(() => {
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '增加伤病数据成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      // console.log(row)
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateInjury(tempData).then(() => {
            // const index = this.list.findIndex((v) => v.id === this.temp.id)
            // this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            setTimeout(() => {
              this.listLoading = false
            }, 5 * 1000)
            this.getList()
            this.$notify({
              title: '成功',
              message: '修改伤病数据成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    }, dateFormat(fmt, date) {
      let ret = ''
      date = new Date(date)
      const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      for (const k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
          )
        }
      }
      return fmt
    },
    // 表格删除
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteInjury(row.Injury_id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then((response) => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then((excel) => {
        const tHeader = ['伤员姓名', '受伤时间', '伤病类型', '伤病部位', '损伤程度', '受伤地点', '受伤场景', '国家队队医', '俱乐部队医', '恢复时间', '治疗方法']
        const filterVal = [
          'Player_name', 'Injury_time', 'Injury_type', 'Injury_position', 'Injury_level', 'Injury_location', 'Injury_scene', 'Nation_doctorname', 'Club_doctorname', 'Recovery_time', 'Injury_method'
        ]
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    handlemodelDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['伤员姓名', '受伤时间', '伤病类型', '伤病部位', '损伤程度', '受伤地点', '受伤场景', '国家队队医', '俱乐部队医', '恢复时间', '治疗方法']
        const filterVal = []
        const list = this.list
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
    },
    reset() {
      Object.assign(this.$data, this.$options.data())
      this.getList()
    }
  }
}
</script>

<style scoped>
  ::v-deep.el-input__inner{
    background-color: #f5f5f5;}
  ::v-deep.el-textarea__inner{
    background-color: #f5f5f5;}
  ::v-deep.el-select__dropdown_item{
    background-color: #f5f5f5;}
  ::v-deep.number.active{
    Background-color: #9C000D;}
  ::v-deep .el-button--mini.is-round {
      padding: 5px 15px;
  }
  ::v-deep .el-slider__button {
    border: 1px solid #9C000D;
    background-color: #fff;
    margin-top: 5px;
    width: 12px;
    height: 12px;
  }
  ::v-deep .el-slider__bar {
    height: 12px;
    background-color: #9C000D;
  }
  ::v-deep .el-slider__stop {
    width: 0;
  }
  ::v-deep .el-slider__runway {
    height: 12px;
    background-color: #979797;
  }
  ::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    color: #9C000D;
    background-color: #FFFFFF;
    border-color: #9C000D;
    -webkit-box-shadow: 0 0 0 0 #9C000D;
    box-shadow: -1px 0 0 0 #9C000D;
    border-radius: 12px;
    height: 24px;
  }
  ::v-deep .el-radio-button--mini .el-radio-button__inner {
    padding: 5px 15px;
    font-size: 12px;
    border-radius: 12px;
    height: 24px;
  }
  ::v-deep .el-dialog {
    border-radius: 14px;
    width: 50%;
  }
  ::v-deep .el-dialog__header {
    border-bottom: 5px solid #eeeeee;
  }
  ::v-deep .el-dialog__body {
    padding: 10px 20px;
  }
  ::v-deep .el-form-item {
    margin-bottom: 10px;
  }
  ::v-deep .el-form--label-top .el-form-item__label {
    padding: 0;
  }
  ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #9C000D;
    border-color: #9C000D;
  }
  ::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #9C000D;
  }
  ::v-deep .el-checkbox__inner:hover {
    border: 1px solid #9C000D;
  }
  ::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: rgba(156, 0, 13, 0.9);
  }
  ::v-deep .el-radio-button__inner:hover {
    color:#9C000D
  }
  ::v-deep .el-input--mini .el-input__inner {
    border-radius: 10px;
    height: 28px;
  }
</style>
   